package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.mapper.UsersMapper;
import com.example.demo.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UsersController {
    @Autowired
    UsersMapper usersMapper;
    //实现获取用户列表
    @GetMapping("/allUser")
    public List<Users> getUsers(){  return usersMapper.selectList(null); }
    //实现添加用户
    @PostMapping("/addUser")
    public Users addUsers(@RequestBody Users user) {
        usersMapper.insert(user);
        return user;
    }
    //实现修改用户
    @PutMapping("/updateUser/{id}")
    public Users updateUser(@PathVariable("id") int id, @RequestBody Users user) {
        Users existingUser = usersMapper.selectById(id);
        if (existingUser != null) {
            user.setId(id);
            usersMapper.updateById(user);
            return user;
        } else {
            return null;
        }
    }
    //实现删除用户
    @DeleteMapping("/delUser/{id}")
    public int delUser(@PathVariable("id") int id) {
        return usersMapper.deleteById(id);
    }
    //实现查询用户
    @GetMapping("/userByName/{name}")
    public List<Users> findByName(@PathVariable String name) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return usersMapper.selectList(queryWrapper);
    }
    //实现用户分页
    @GetMapping("/findByPage")
    public IPage getUserList(@RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize) {
        Page<Users> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id"); // 根据id字段降序排序
        page.addOrder(OrderItem.desc("id")); // 添加降序排序条件
        IPage ipage = usersMapper.selectPage(page,null);
        return ipage;
    }
}

